package models

import (
	"gintest/database"
	"time"
)

//表结构
type Adpos struct {
	Id        int    `json:"id" gorm:"column:id;primary_key" form:"id"`
	Title string `json:"title" gorm:"column:title" form:"title"`
	Sort  int `json:"sort" gorm:"column:sort" form:"sort"`
	CreateAt time.Time  `json:"create_at" gorm:"column:create_at;type:datetime" time_format:"2006-01-02 15:04:05" form:"create_at"`
	UpdateAt time.Time  `json:"update_at" gorm:"column:update_at;type:datetime" time_format:"2006-01-02 15:04:05" form:"update_at"`
	DeleteAt time.Time  `json:"delete_at" gorm:"column:delete_at;type:datetime" time_format:"2006-01-02 15:04:05" form:"delete_at"`
	Desc string `json:"desc" gorm:"column:desc" form:"desc"`
}
func (Adpos) TableName() string {
	return "adpos"
}

func GetAdposList(page uint64,pagesize uint64,keyword string)(data []Adpos,total uint64){
	var offset=(page-1)*pagesize
	db:=database.SqlDB.Model(Adpos{})

	if len(keyword)!=0{
		db=db.Where("title like ?","%"+keyword+"%")
	}

	db=db.Where("delete_at = 0 or delete_at is null")

	db.Offset(offset).Limit(pagesize).Order("id desc").Find(&data)
	db.Model(Adpos{}).Count(&total)

	return data,total
}
func AddAdpos(data *Adpos) error{
	if data.UpdateAt.IsZero(){
		data.UpdateAt=time.Now()
	}
	if data.CreateAt.IsZero(){
		data.CreateAt=time.Now()
	}
	return database.SqlDB.Model(Adpos{}).Create(data).Error
}
func DelAdposByIds(ids []int) error{
	//return database.SqlDB.Model(Adpos{}).Where("id in (?)",ids).Delete(Adpos{}).Error
	return database.SqlDB.Model(Adpos{}).Where("id in (?) and (delete_at = 0 or delete_at is null)",ids).Update("delete_at",time.Now().Local().String()).Error
}
func GetAdposById(id int) (data Adpos){
	database.SqlDB.Model(Adpos{}).Where("id=?",id).First(&data);
	return data
}
/*func EditAdposById(data *Adpos){
	if data.UpdateAt.IsZero(){
		data.UpdateAt=time.Now()
	}
	database.SqlDB.Model(Adpos{}).Save(data)
}*/
/**
	更新
	id 编号
    data map[string]interface{}
*/
func EditAdposById(id int,data interface{}) error{
	//update_at不存在，填充当前时间
	if _, has := data.(map[string]interface{})["update_at"]; !has {
		data.(map[string]interface{})["update_at"]=time.Now()
	}
	return database.SqlDB.Model(&Adpos{}).Where("id=?",id).Updates(data).Error
}